 <!--
 * 厦门大学计算机专业 | 前华为工程师
 * 专注《零基础学编程系列》  http://lblbc.cn/blog
 * 包含：Java | 安卓 | 前端 | Flutter | iOS | 小程序 | 鸿蒙
 * 公众号：蓝不蓝编程
 -->
<template>
  <div class="wrapper">
    <div class="array">{{ arrayStr }}</div>
    <div class="btn-row">
      <div class="btn" @click="shuffle">打乱</div>
      <div class="btn btn-right" @click="sort">排序</div>
    </div>
  </div>
</template>
  
<script lang="ts">
export default {
  data() {
    return {
      array: [],
      arrayStr: ''
    }
  },
  mounted() {
    this.shuffle()
  },
  methods: {
    shuffle() {
      let array = [2, 1, 5, 4, 3]
      this.array = array
      this.arrayStr = this.convertToStr(array)
    },
    sort() {
      let array = this.array
      var first = 0
      var last = array.length - 1
      this.mergeSort(first, last)
      this.array = array
      this.arrayStr = this.convertToStr(array)
    },
    mergeSort(first: number, last: number) {
      if (first < last) {
        var mid = Math.floor((first + last) / 2)
        this.mergeSort(first, mid)
        this.mergeSort(mid + 1, last)
        this.binaryMerge(first, mid, last)
      }
    },
    binaryMerge(first: number, mid: number, last: number) {
      let array = this.array
      var tmpArray = Array(array.length).fill(0)
      var left: number, right: number, index: number
      for (index = first; index <= last; index++) {
        tmpArray[index] = array[index]
      }
      index = first
      left = first
      right = mid + 1
      for (; left <= mid && right <= last && index <= last; index++) {
        if (tmpArray[left] <= tmpArray[right]) {
          array[index] = tmpArray[left++]
        } else {
          array[index] = tmpArray[right++]
        }
      }
      while (left <= mid) {
        array[index++] = tmpArray[left++]
      }
      while (right <= last) {
        array[index++] = tmpArray[right++]
      }
    },
    convertToStr(array: number[]) {
      var result = ''
      for (let i = 0; i < array.length; i++) {
        result += array[i] + ' '
      }
      return result
    }
  }
}
</script>
  
<style scoped>
.wrapper {
  display: flex;
  justify-content: center;
  flex-direction: column;
  align-items: center;
  margin-top: 50px;
}
.array {
  font-size: 40px;
}
.btn-row {
  margin-top: 20px;
}

.btn {
  display: inline-block;
  padding: 0 20px;
  height: 40px;
  line-height: 40px;
  border-radius: 5px;
  cursor: pointer;
  text-align: center;
  color: #f9f6f2;
  background: #418df9;
}

.btn-right {
  margin-left: 10px;
}
</style>
  